package com.tools.function.excel;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tools.function.R;

/**
 * 随机产生数据,读取SD卡下面的Excel文件(需要添加SD卡读取权限)
 * 
 * @author 蔡有飞 E-mail: caiyoufei@looip.cn
 * @version 创建时间：2014-2-11 下午6:08:43
 */
public class ExcelMainActivity extends Activity {
	// 筛选数据按钮
	private Button cButtonMatch;
	// 产生数据按钮
	private Button cButtonCreate;
	// 产生数据显示
	private TextView cTextViewNumber;
	// 筛选数据显示
	private TextView cTextViewData;
	// 产生数据显示
	private TextView cTextViewOldData;
	// 上期数据显示
	private TextView cTextViewPreviousData;
	// 筛选数据个数显示
	private TextView cTextViewCount;
	// 筛选数据相同个数输入
	private EditText cEditText;
	// 随机产生的数组
	private int dest[] = new int[7];
	// 是否已经点击产生数据
	private boolean isCreate = false;
	// 筛选数据是否完成
	private boolean isComptele = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_excel_main);
		init();
	}

	/**
	 * 初始化
	 */
	@SuppressLint("NewApi")
	private void init() {
		cButtonMatch = (Button) findViewById(R.id.btn_match);
		cButtonCreate = (Button) findViewById(R.id.btn_create);
		cTextViewNumber = (TextView) findViewById(R.id.tv_number);
		cTextViewData = (TextView) findViewById(R.id.tv_data);
		cTextViewOldData = (TextView) findViewById(R.id.tv_old_data);
		cTextViewPreviousData = (TextView) findViewById(R.id.tv_previous_data);
		cTextViewCount = (TextView) findViewById(R.id.tv_count);
		cEditText = (EditText) findViewById(R.id.et_select);
		cButtonCreate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isComptele) {
					getArray();
					isCreate = true;
					// 产生随机数后立即执行筛选
					// cButtonMatch.callOnClick();
				}
			}
		});
		cButtonMatch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isCreate) {
					isComptele = false;
					getData();
				} else {
					Toast.makeText(ExcelMainActivity.this, "请先产生随机数",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	/**
	 * 产生一组随机数
	 */
	private void getArray() {
		// 和的最大值(2014-2-11之前)
		int max = 170;
		// 和的最小值(2014-2-11之前)
		int min = 41;
		// 前六位数之和、相同数字的数量
		int total = 0;
		// 产生一组数，前6位之和介于max和min之间
		while (true) {
			total = 0;
			for (int i = 0; i < dest.length - 1; i++) {
				dest[i] = ((int) (Math.random() * 33 + 1));
				for (int j = 0; j < i; j++) {
					if (dest[i] == dest[j]) {
						i = i - 1;
						break;
					}
				}
			}
			dest[6] = ((int) (Math.random() * 16 + 1));
			for (int j = 0; j < dest.length - 1; j++) {
				total += dest[j];
			}
			if (total <= max && total >= min) {
				break;
			}
		}
		// 将产生的数组前6位按照从小到大排序
		for (int i = 0; i < dest.length - 2; i++) {
			for (int j = i; j < dest.length - 1; j++) {
				if (dest[i] > dest[j]) {
					int temp = 0;
					temp = dest[j];
					dest[j] = dest[i];
					dest[i] = temp;
				}
			}
		}
		cTextViewNumber.setText(dest[0] + "\t\t" + dest[1] + "\t\t" + dest[2]
				+ "\t\t" + dest[3] + "\t\t" + dest[4] + "\t\t" + dest[5]
				+ "\t\t\t" + dest[6]);
	}

	/**
	 * 获取SD卡数据并进行筛选
	 */
	private void getData() {
		cTextViewOldData.setText(dest[0] + "\t\t\t" + dest[1] + "\t\t\t"
				+ dest[2] + "\t\t\t" + dest[3] + "\t\t\t" + dest[4] + "\t\t\t"
				+ dest[5] + "\t\t\t\t" + dest[6]);
		// 相同数字的数量
		int total = 0;
		int count = 0;
		// 建立需要打开获取数据的Excel文件
		File file = new File("/sdcard/2014.xls");
		// 建立需要写入文件的文件夹
		// File file2 = new File("/sdcard/2014");
		// if (!file2.exists()) {
		// file2.mkdir();
		// }
		// 需要写入的内容
		String data = "";
		try {
			// 从Excel中获取数据到数组
			String[][] array = getData(file, 0);
			int length = array.length - 1;
			cTextViewPreviousData.setText(array[length][1].toString()
					+ "\t\t\t" + array[length][2].toString() + "\t\t\t"
					+ array[length][3].toString() + "\t\t\t"
					+ array[length][4].toString() + "\t\t\t"
					+ array[length][5].toString() + "\t\t\t"
					+ array[length][6].toString() + "\t\t\t\t"
					+ array[length][8].toString());
			for (int j = 0; j < array.length; j++) {
				total = 0;
				for (int i = 0; i < dest.length - 1; i++) {
					for (int k = 0; k < 9; k++) {
						if (k == 0 || k == 7 || k == 8) {
							continue;
						} else {
							// 将获取的数组与随机产生的数组对比
							if ((dest[i] + "").equals(array[j][k].toString()
									.replace(".0", ""))) {
								total++;
							}
						}
					}
				}
				if (total == 6) {
					System.out.println(array[j][0]);
				}
				// 统计满足要求的数组个数和信息
				int num = 0;
				if (cEditText.getText().toString().equals("")) {
					num = 4;
				} else {
					try {
						num = Integer.parseInt(cEditText.getText().toString());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (total >= num) {
					count++;
					data += array[j][1].toString() + "\t\t\t\t"
							+ array[j][2].toString() + "\t\t\t\t"
							+ array[j][3].toString() + "\t\t\t\t"
							+ array[j][4].toString() + "\t\t\t\t"
							+ array[j][5].toString() + "\t\t\t\t"
							+ array[j][6].toString() + "\t\t\t\t\t"
							+ array[j][8].toString() + "\n";
				}
			}
			if (count > 0) {
				cTextViewCount.setText("共有" + count + "组历史数据与当前产生数据类似");
				cTextViewData.setVisibility(View.VISIBLE);
			} else {
				cTextViewCount.setText("没有类似的历史数据");
				cTextViewData.setVisibility(View.GONE);
				return;
			}

			// 将随机产生的数组和符合要求的数组合并到一起
			cTextViewData.setText(data);
			isComptele = true;
			// 将数据写入文件中
			// File f = new File("D:\\2014\\" + "2014.xls");
			// if (!f.exists()) {
			// f.createNewFile();// 不存在则创建
			// } else {
			// f.delete();
			// }
			// BufferedWriter output = new BufferedWriter(new FileWriter(f));
			// output.write(data);
			// output.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 对Excel文件进行数据读取
	 * 
	 * @param file
	 *            需要读取的Excel文件
	 * @param ignoreRows
	 *            从第几行开始读取
	 */
	public static String[][] getData(File file, int ignoreRows)

	throws FileNotFoundException, IOException {

		List<String[]> result = new ArrayList<String[]>();

		int rowSize = 0;

		BufferedInputStream in = new BufferedInputStream(new FileInputStream(

		file));

		// 打开HSSFWorkbook

		POIFSFileSystem fs = new POIFSFileSystem(in);

		HSSFWorkbook wb = new HSSFWorkbook(fs);

		HSSFCell cell = null;

		for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {

			HSSFSheet st = wb.getSheetAt(sheetIndex);

			// 第一行为标题，不取

			for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {

				HSSFRow row = st.getRow(rowIndex);

				if (row == null) {

					continue;

				}

				int tempRowSize = row.getLastCellNum() + 1;

				if (tempRowSize > rowSize) {

					rowSize = tempRowSize;

				}

				String[] values = new String[rowSize];

				Arrays.fill(values, "");

				boolean hasValue = false;

				for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {

					String value = "";

					cell = row.getCell(columnIndex);

					if (cell != null) {

						// 注意：一定要设成这个，否则可能会出现乱码

						cell.setEncoding(HSSFCell.ENCODING_UTF_16);

						switch (cell.getCellType()) {

						case HSSFCell.CELL_TYPE_STRING:

							value = cell.getStringCellValue();

							break;

						case HSSFCell.CELL_TYPE_NUMERIC:

							if (HSSFDateUtil.isCellDateFormatted(cell)) {

								Date date = cell.getDateCellValue();

								if (date != null) {

									value = new SimpleDateFormat("yyyy-MM-dd")

									.format(date);

								} else {

									value = "";

								}

							} else {

								value = new DecimalFormat("0").format(cell

								.getNumericCellValue());

							}

							break;

						case HSSFCell.CELL_TYPE_FORMULA:

							// 导入时如果为公式生成的数据则无值

							if (!cell.getStringCellValue().equals("")) {

								value = cell.getStringCellValue();

							} else {

								value = cell.getNumericCellValue() + "";

							}

							break;

						case HSSFCell.CELL_TYPE_BLANK:

							break;

						case HSSFCell.CELL_TYPE_ERROR:

							value = "";

							break;

						case HSSFCell.CELL_TYPE_BOOLEAN:

							value = (cell.getBooleanCellValue() == true ? "Y"

							: "N");

							break;

						default:

							value = "";

						}

					}

					if (columnIndex == 0 && value.trim().equals("")) {

						break;

					}

					values[columnIndex] = rightTrim(value);

					hasValue = true;

				}

				if (hasValue) {

					result.add(values);

				}

			}

		}

		in.close();

		String[][] returnArray = new String[result.size()][rowSize];

		for (int i = 0; i < returnArray.length; i++) {

			returnArray[i] = (String[]) result.get(i);

		}

		return returnArray;

	}

	/**
	 * 
	 * 去掉字符串右边的空格
	 * 
	 * @param str
	 *            要处理的字符串
	 * 
	 * @return 处理后的字符串
	 */

	public static String rightTrim(String str) {

		if (str == null) {

			return "";

		}

		int length = str.length();

		for (int i = length - 1; i >= 0; i--) {

			if (str.charAt(i) != 0x20) {

				break;

			}

			length--;

		}

		return str.substring(0, length);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, Menu.FIRST + 1, 1, "关于").setIcon(

		android.R.drawable.ic_menu_info_details);

		menu.add(Menu.NONE, Menu.FIRST + 2, 2, "帮助").setIcon(

		android.R.drawable.ic_menu_help);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			new AlertDialog.Builder(this)
					.setMessage(
							"作者:蔡有飞\n\n版权归上海持创信息技术有限公司所有\n\n任何人不得修改本程序后宣传本作品 ")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(
										DialogInterface dialoginterface, int i) {
									// 按钮事件
								}
							}).setIcon(android.R.drawable.ic_menu_info_details)
					.setTitle("作者").show();
			break;

		case Menu.FIRST + 2:

			new AlertDialog.Builder(this)
					.setMessage("使用过程中如有问题或建议\n请发邮件至caiyoufei@looip.cn")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(
										DialogInterface dialoginterface, int i) {
									// 按钮事件
								}
							}).setTitle("帮助")
					.setIcon(android.R.drawable.ic_menu_help).show();
			break;
		}
		return false;
	}

}
